<template>
  <NavBar />
  <video-player v-show="videoVisible" :key="videoProps.key" :title="videoProps.title" :video-url="videoProps.videoUrl" :cover="videoProps.cover" />
  <img v-show="!videoVisible" style="width: 100%" :src="courseInfo.bannerUrl"  alt=""/>
  <van-tabs v-model:active="active">
    <van-tab title="课程介绍">
      <img :src="courseInfo.detailUrl" style="width: 100%"  alt=""/>
    </van-tab>
    <van-tab title="课程目录">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了">
        <van-cell v-for="(item, index) in catalogueList" :key="item.id" :label="'时长 '+ item.durationTime" center @click="playVideoHandle(item,index)" is-link>
          <template #title>
            <span>{{ item.catalogueName }}&nbsp;&nbsp;</span>
            <van-tag v-if="item.isLock===1" type="danger">试听</van-tag>
          </template>
        </van-cell>
      </van-list>
    </van-tab>
    <van-tab title="评论">

    </van-tab>
  </van-tabs>

<!--  <div style="height: 50px">-->
    <div class="footer">
<!--      <div>-->
<!--        <span>{{courseInfo.presentPrice}}</span><br/>-->
<!--        <span>{{courseInfo.price}}</span><br/>-->
<!--      </div>-->
<!--      <van-button class="submit_button" type="primary" size="small" round @submit="addOrder()">加入购物车</van-button>-->
      <van-button class="submit_button" type="primary" size="small" round @click="createOrderHandle()">立即报名</van-button>
    </div>
<!--  </div>-->
</template>
<script>
import NavBar from "@/components/layout/nav-bar";
import VideoPlayer from "@/components/video/video-player"
import { useRoute } from "vue-router";
import { onBeforeMount, reactive, toRefs, ref } from "vue"
import { createOrderV3 } from "@/api/order";
import { getCourseInfo, getCourseCatalogueList } from "@/api/course";
import { Toast } from "vant"
import http from "@/utils/http";
export default {
  components:{
    NavBar,VideoPlayer
  },
  setup(){
    const active = ref(0)
    const route = useRoute()
    const state = reactive({
      videoVisible: false,
      videoProps: {},
      loading: false,
      finished: false,
      courseInfo: {},
      catalogueList: []
    })

    onBeforeMount(()=>{
      getCourseInfo(route.params.id).then(({data: res}) => {
        if (res.code !==0){
          return Toast.fail(res.msg)
        }
        state.courseInfo = res.data;
      }).then(()=>{
        http.get(`/course/catalogue/${state.courseInfo.id}`).then(({data: res}) => {
          if (res.code !==0){
            return Toast.fail(res.msg)
          }
          state.catalogueList = res.data;
          state.loading = true;
          state.finished = true;
        })
      })
    })

    const playVideoHandle=((item,index) => {
      state.videoVisible = false;
      if(item.isLock===0){
        return Toast('该课时需要解锁！');
      }
      if(state.videoProps.key !== index){
        state.videoProps.key = index;
        state.videoProps.title = item.catalogueName;
        state.videoProps.videoUrl = item.videoUrl;
        state.videoProps.cover = state.courseInfo.bannerUrl;
      }else {
        Toast('您正在观看此视频！');
      }
      state.videoVisible = true
    })

    const createOrderHandle=(()=>{
      createOrderV3().then(({data: res})=>{
        if (res.code !== 0) {
          return Toast.fail(res.msg)
        }
        if (typeof WeixinJSBridge === 'undefined') { // 微信浏览器内置对象。参考微信官方文档
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady(res.data), false)
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady(res.data))
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(res.data))
          }
        } else {
          console.log('准备调用微信支付')
          onBridgeReady(res.data)
        }
      })
    })

    function onBridgeReady(data) {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          'appId': data.appId, // 公众号名称，由商户传入
          'timeStamp': data.timeStamp, // 时间戳，自1970年以来的秒数
          'nonceStr': data.nonceStr, // 随机串
          'package': data.packageValue, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
          'signType': data.signType, // 微信签名方式：
          'paySign': data.paySign // 微信签名
        },
        function(res) {
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            return Toast.success('支付成功')
          } else {
            return Toast.fail('支付失败')
          }
        })
      return undefined;
    }

    return {
      active,
      ...toRefs(state),
      playVideoHandle,
      createOrderHandle
    };
  }
}
</script>

<style lang="less" scoped>
.footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  position: fixed;
  bottom: 0;
  padding: .45rem 0;
  .submit_button {
    border: 0;
    background: linear-gradient(to right,#ff6034,#ee0a24);
    width: 6rem;
    margin: 0 5px 0 0;
  }

}
</style>
